# /usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
@File    : user.py
@Time    : 2020/2/2 0002 11:12
@Author  : zhangbing
@Email   : 18829172841@163.com
@Software: PyCharm
"""

from flask import render_template, request, redirect, url_for, session

from App.ext import cache
from ..models import User
from flask import Blueprint

userauth = Blueprint("userauth", __name__)


@userauth.route('/list/')
@cache.cached(timeout=100)
def userlist():
    if request.method == "GET":
        users = User.query.all()
        return render_template("user/user_list.html", users=users)


@userauth.route('/register/', methods=["GET", "POST"])
def useradd():
    if request.method == "GET":
        return render_template('user/user_add.html')
    elif request.method == "POST":
        user = User()
        user.name = request.form["username"]
        user.loginname = request.form["loginname"]
        user.password = request.form["password"]
        user.email = request.form["email"]
        try:
            user.save()
            return redirect(url_for('userauth.userlist'))
        except  Exception  as e:
            print('1234768679789', e)
            return "user  add  failed"


@userauth.route('/login/', methods=["GET", "POST"])
def user_login():
    if request.method == "GET":
        return render_template("user/user_login.html")
    elif request.method == "POST":
        user = User.query.filter(User.loginname == request.form["loginname"]).first()
        if user is None:
            return "user {} not exists".format(request.form["loginname"])
        if user.password == request.form["password"]:
            return redirect(url_for('userauth.index'))


@userauth.route('/')
def index():
    return render_template("user/index.html")


if __name__ == "__main__":
    pass
